package com.huawei.hwclouds.lubanops.demo.common.exception;

import com.huawei.hwclouds.lubanops.demo.common.constants.Constants;
import com.huawei.hwclouds.lubanops.demo.common.exception.common.InternalErrorException;

/**
 * 错误码的解析器
 * 错误码格式是：apm2.00000001  apm2是固定的服务名，后面8位，前四位是微服务名字，后四位是错误码名字
 *
 * @author y00438022
 * @since 2020/12/30
 **/
public class ErrorCodeParser {

    /**
     * 序列化
     *
     * @param serviceCode
     * @param errorCode
     * @return
     */
    public static String toErrorCodeString(String serviceCode, String errorCode) {
        if (serviceCode.length() != 4) {
            throw new InternalErrorException("serviceCode must be 4 length");
        }

        if (errorCode.length() != 4) {
            throw new InternalErrorException("serviceCode must be 4 length");
        }

        return Constants.ERROR_CODE_PREFIX + serviceCode + errorCode;
    }

    /**
     * 解析出字段来
     *
     * @param inputCode 输入的错误码
     * @return
     */
    public static String[] parseString(String inputCode) {
        if (inputCode == null) {
            throw new InternalErrorException("inputCode is null");
        }

        String subCode;
        if (inputCode.startsWith(Constants.ERROR_CODE_PREFIX)) {
            subCode = inputCode.substring(Constants.ERROR_CODE_PREFIX.length());
        } else {
            throw new InternalErrorException("invalid error code:" + inputCode);
        }

        if (subCode.length() != 8) {
            throw new InternalErrorException("invalid error code:" + inputCode);
        }

        String serviceCode = subCode.substring(0, 4);
        String code = subCode.substring(4);
        String[] ss = new String[3];
        ss[0] = Constants.ERROR_CODE_PREFIX;
        ss[1] = serviceCode;
        ss[2] = code;
        return ss;
    }
}
